package com.db.common.aop;

import com.db.common.annotation.RequiredMenu;
import com.db.common.util.IPUtils;
import com.db.pojo.SysLog;
import com.db.service.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class SysMenuAspect {


    @Autowired
    private SysLogService sysLogService;

    @Around("@annotation(requiredMenu)")
    public Object doAround(ProceedingJoinPoint jp, RequiredMenu requiredMenu) {

        try {
            long start = System.currentTimeMillis();
            Object object = jp.proceed();
            long end = System.currentTimeMillis();

            saveLog(jp, requiredMenu, (end - start));
            return object;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            throw new RuntimeException(throwable); //将检查异常抛给运行异常
        }
    }

    private void saveLog(ProceedingJoinPoint jp, RequiredMenu requiredMenu, long time) {

        SysLog sysLog = new SysLog();
        sysLog.setUsername("admin");
        sysLog.setTime(time);
        sysLog.setParams(Arrays.toString(jp.getArgs()));
        sysLog.setOperation(requiredMenu.operation());
        sysLog.setMethod(getMethod(jp)); //方法全名
        sysLog.setIp(IPUtils.getIpAddr());

        sysLogService.insertObject(sysLog);
    }

    private String getMethod(ProceedingJoinPoint jp) {

        Class<?> clazz = jp.getTarget().getClass();
        String className = clazz.getName();
        Signature signature = jp.getSignature();
        String methodName = signature.getName();

        return className + "." + methodName;
    }

}
